﻿using System;
using System.Collections.Generic;
using System.Linq;
using Core.Interfaces;
using Core.Model;
using Infrastructure.Database;

namespace Infrastructure.Repositories
{
    public class CatalogRepository : ICatalogRepository
    {
        #region ICatalogRepository Members

        public List<Product> GetProductsByCategory(string categoryId)
        {
            if (string.IsNullOrEmpty(categoryId))
                return null;

            using (var ctx = new PetshopDbContext())
            {
                return ctx.Products.Where(c => c.Category.CategoryId == categoryId).ToList();
            }
        }

        public List<Item> GetItemsByProduct(string productId)
        {
            if (productId == null) throw new ArgumentNullException("productId");

            using (var ctx = new PetshopDbContext())
            {
                return ctx.Items.Where(i => i.Product.ProductId == productId).ToList();
            }
        }


        public Category GetCategory(string categoryId)
        {
            if (categoryId == null) throw new ArgumentNullException("categoryId");
            using (var ctx = new PetshopDbContext())
            {
                return ctx.Categories.SingleOrDefault(c => c.CategoryId == categoryId);
            }
        }


        public Product GetProduct(string productId)
        {
            if (productId == null) throw new ArgumentNullException("productId");
            using (var ctx = new PetshopDbContext())
            {
                return ctx.Products.SingleOrDefault(c => c.ProductId == productId);
            }
        }

        public List<Item> GetItemsPerProduct(string productId)
        {
            if (productId == null) throw new ArgumentNullException("productId");
            using (var ctx = new PetshopDbContext())
            {
                return ctx.Items.Where(c => c.Product.ProductId == productId).ToList();
            }
        }


        public Item GetItem(string itemId)
        {
            if (itemId == null) throw new ArgumentNullException("itemId");
            using (var ctx = new PetshopDbContext())
            {
                return ctx.Items.Include("Product").SingleOrDefault(c => c.ItemId == itemId);
            }
        }

        #endregion
    }
}